<template>
  <div class="main">
    <a-icon class="QRcodeIcon" :component="allIcon.QRcodeIcon"/>
    <a-form-model ref="form" class="user-layout-register" :model="form" :rules="rules">
      <a-page-header title="用户注册" />
      <a-form-model-item prop="username">
        <a-input v-model="form.username" size="large" placeholder="账户" >
          <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)'}"/>
        </a-input>
      </a-form-model-item>
      <a-form-model-item prop="password">
        <a-input-password v-model="form.password" size="large" placeholder="密码">
          <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }"/>
        </a-input-password>
      </a-form-model-item>
      <a-form-model-item prop="confirmPassword">
        <a-input-password v-model="form.confirmPassword" size="large" placeholder="确认密码">
          <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }"/>
        </a-input-password>
      </a-form-model-item>
      <a-row :gutter="16" v-if="captchaOnOff">
        <a-col class="gutter-row" :span="16">
          <a-form-model-item prop="code">
            <a-input v-model="form.code" size="large" type="text" autocomplete="off" placeholder="验证码">
              <a-icon slot="prefix" type="security-scan" :style="{ color: 'rgba(0,0,0,.25)' }"/>
            </a-input>
          </a-form-model-item>
        </a-col>
        <a-col class="gutter-row" :span="8">
          <img class="getCaptcha" :src="codeUrl" @click="getCode">
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col class="gutter-row" :span="10">
          <a-form-model-item prop="mobile">
            <a-input v-model="form.mobile" size="large" placeholder="手机号码" >
              <a-icon slot="prefix" type="mobile" :style="{ color: 'rgba(0,0,0,.25)'}"/>
            </a-input>
          </a-form-model-item>
        </a-col>
        <a-col class="gutter-row" :span="7">
          <a-form-model-item prop="mobilecode">
            <a-input v-model="form.mobilecode" size="large" type="text" autocomplete="off" placeholder="验证码">
              <a-icon slot="prefix" :component="allIcon.validCodeIcon" :style="{ color: 'rgba(0,0,0,.25)' }"/>
            </a-input>
          </a-form-model-item>
        </a-col>
        <a-col class="gutter-row" :span="7">
          <a-button style="height:40px;line-height:40px;width:100px;" :disabled="state.smsSendBtn" @click.stop.prevent="getMobileCode" v-text="!state.smsSendBtn && '获取验证码'||(state.time+' s')"></a-button>
        </a-col>
      </a-row>
      <a-form-model-item>
        <a-checkbox-group style="height: 30px;line-height: 30px;" v-model="form.agreement" :options="[{value: 'agreement'}]">
          <template slot="label" slot-scope="option">
            <a href="javascript:;" @click="showAgreement">接受条款及协议</a>
          </template>
        </a-checkbox-group>
        <div style="float: right;line-height: 30px;">
          已有账号？<router-link to="/user/login">立即登录</router-link>
        </div>
      </a-form-model-item>
      <a-form-item style="margin-top:14px">
        <a-button
          size="large"
          type="primary"
          htmlType="submit"
          class="register-button"
          :loading="logining"
          :disabled="logining"
          @click="handleSubmit"
        >注册</a-button>
      </a-form-item>
    </a-form-model>
    <agreement ref="agreement" />
  </div>
</template>

<script>

import { mapActions } from 'vuex'
import { timeFix } from '@/utils/util'
import { getCodeImg } from '@/api/login'
import allIcon from '@/core/icons'
import Agreement from './Agreement'

export default {
  name: 'Register',
  components: {
    allIcon,
    Agreement
  },
  data () {
    return {
      allIcon,
      codeUrl: '',
      form: {
        username: '',
        password: '',
        confirmPassword: '',
        code: undefined,
        mobile: '',
        mobilecode: '',
        agreement: ['agreement'],
        uuid: ''
      },
      state: {
        time: 60,
        smsSendBtn: false
      },
      // 验证码开关
      captchaOnOff: true,
      rules: {
        username: [{ required: true, message: '请输入帐户名', validator: this.handleUserCheck, trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        confirmPassword: [{ required: true, message: '请再次输入密码', trigger: 'blur' }],
        code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
        mobile: [{ required: true, message: '请输入正确的手机号', validator: this.handlePhoneCheck, trigger: 'blur' }],
        code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
        mobilecode: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
      },
      logining: false
    }
  },
  created () {
    this.getCode()
  },
  methods: {
    getCode () {
      const params = {
        smsmode: "REGISTER",
        uuid: this.form.uuid
      }
      getCodeImg('REGISTER').then(res => {
        this.captchaOnOff = !!res.data.captchaOnOff
        if (this.captchaOnOff) {
          this.codeUrl = 'data:image/gif;base64,' + res.data.img
          this.form.uuid = res.data.uuid
        }
      })
    },
    getMobileCode () {
      this.$refs.form.validateField(['mobile'], error => {
        if (!error) {
          this.state.smsSendBtn = true;
          let interval = window.setInterval(() => {
            if (this.state.time-- <= 0) {
              this.state.time = 60;
              this.state.smsSendBtn = false;
              window.clearInterval(interval);
            }
          }, 1000);
          const hide = this.$message.loading('验证码发送中..', 0);
          const params = {
            mobile: this.form.mobile,
            smsmode: "REGISTER",
            uuid: this.form.uuid
          }
          postAction("/captchaSms", params).then((res) => {
            if (!res.success) {
              this.registerFailed(res.message);
              setTimeout(hide, 0);
            }
            setTimeout(hide, 500);
          }).catch(err => {
            setTimeout(hide, 1);
            clearInterval(interval);
            this.state.time = 60;
            this.state.smsSendBtn = false;
            this.requestFailed(err);
          });
        }
      })
    },
    ...mapActions(['Register']),
    handleSubmit () {
      // 关闭登录过期的提示框
      this.$notification.close('loginExpireTip')
      this.logining = true
      this.$refs.form.validate(valid => {
        if (valid) {
          this.Register(this.form)
            .then((res) => this.loginSuccess(res))
            .catch(err => this.requestFailed(err))
            .finally(() => {
              this.logining = false
            })
        } else {
          setTimeout(() => {
            this.logining = false
          }, 600)
          if (this.captchaOnOff) {
            this.getCode()
          }
        }
      })
    },
    loginSuccess (res) {
      this.$router.push({ path: '/' })
      // 延迟 1 秒显示欢迎信息
      setTimeout(() => {
        this.$notification.success({
          message: '欢迎',
          description: `${timeFix()}，欢迎回来`
        })
      }, 1000)
    },
    requestFailed (err) {
      this.form.code = undefined
      this.getCode()
      this.$message.error(err)
    },
    showAgreement() {
      this.$nextTick(() => {
        this.$refs.agreement.show()
      })
    }
  }
}
</script>

<style lang="less" scoped>
  .QRcodeIcon{
    position: absolute;
    right:0;
    font-size: 32px;
    color: #1890ff;
    margin-top:5px;
    margin-right:5px;
  }
  .ant-space-align-center{
    color:#8f959e;
    line-height: 30px;
    height: 30px;
  }
  .user-layout-register label{
    font-size: 12px!important;
  }
  .user-layout-register {
    label {
      font-size: 14px;
    }
    .ant-page-header{
      padding:20px 0 15px 0;
    }
    .getCaptcha {
      display: block;
      width: 100%;
      height: 40px;
    }

    button.register-button {
      padding: 0 15px;
      font-size: 16px;
      height: 40px;
      width: 100%;
      border-radius: 4px;
    }
  }

</style>
